import { ContainerHistoryPathModalComponent } from './container-history-path-modal/container-history-path-modal.component';
import { ReportAddressModalComponent } from './../report-address-modal/report-address-modal.component';
import { Component, OnInit, Injector, ViewChild } from '@angular/core';
import { ServiceProxy, SiteDTO } from '@shared/service-proxy/service-proxies';
import { NzTableHelper } from '@shared/helpers/NzTableHelper';
import { AppComponentBase } from '@shared/common/app-component-base';
import { finalize } from 'rxjs/operators';
import { LogisticDetailModalComponent } from './logistic-detail-modal/logistic-detail-modal.component';
import { ProductDetailModalComponent } from './product-detail-modal/product-detail-modal.component';
import { RealOnlineModalComponent } from './real-online-modal/real-online-modal.component';
import { ViewArrivedPlanModalComponent } from './view-arrived-plan-modal/view-arrived-plan-modal.component';
import { WarnAddressListModalComponent } from './warn-address-list-modal/warn-address-list-modal.component';
import { HttpHeaders, HttpClient } from '@angular/common/http';

import * as moment from 'moment';

@Component({
  selector: 'app-container-dispatch',
  templateUrl: './container-dispatch.component.html',
  styleUrls: ['./container-dispatch.component.less']
})
export class ContainerDispatchComponent extends AppComponentBase implements OnInit {
  @ViewChild('logisticDetailModal') logisticDetailModal: LogisticDetailModalComponent;
  @ViewChild('productDetailModal') productDetailModal: ProductDetailModalComponent;
  @ViewChild('reportAddressModal') reportAddressModal: WarnAddressListModalComponent;
  @ViewChild('realOnlineModal') realOnlineModal: RealOnlineModalComponent;
  @ViewChild('historyPathModal') historyPathModal: ContainerHistoryPathModalComponent;
  @ViewChild('arrivedPlanModal') arrivedPlanModal: ViewArrivedPlanModalComponent;
  tableHelper: NzTableHelper;
  sites: SiteDTO[] = [];
  routeParams: any;
  params: string;
  checkStatusList = [];
  currentSiteId: string = "";
  constructor(
    injector: Injector,
    private _service: ServiceProxy,
    private httpClient: HttpClient) {
    super(injector);
    this.tableHelper = new NzTableHelper();
  }

  ngOnInit() {
    this.getSites();

    this.routeParams = {
      launchsiteId: '', destinationsiteId: '', containerCode: '', containerStatus: [1, 3, 5]
    };
    this.currentSiteId = this.appSession.user.siteId;
    this.checkStatusList = [
      { label: this.l('wait_sealing_containers'), value: 1, checked: true },
      { label: this.l('stock_in_transit'), value: 3, checked: true },
      { label: this.l('already_arrived'), value: 5, checked: true }];

    this.load();
  }

  getSites() {
    this._service.getAllSitesBySiteUsingGET().subscribe(result => {
      this.sites = result.result.fieldList;
    })
  }


  load(pageIndex?: number) {
    if (typeof pageIndex !== 'undefined') {
      this.tableHelper.pageIndex = pageIndex || 1;
    }
    this.getList();
  }

  sort(sort: { key: string, value: string }): void {
    this.tableHelper.setSorting = sort;
    this.load();
  }

  getList() {
    // if(this.appSession.user.siteId)
    // {
    //   this.routeParams.destinationsiteId = this.appSession.user.siteId;
    //   this.routeParams.launchsiteId = this.appSession.user.siteId;
    // }

    if (this.routeParams) {
      const checkList = this.checkStatusList.filter(m => m.checked == true);
      this.routeParams.containerStatus = [];
      checkList.forEach(element => {
        if (element.checked) {
          this.routeParams.containerStatus.push(element.value);
        }
      });
      this.params = JSON.stringify(this.routeParams);
    }


    this._service.searchAllDispatchPageUsingGET(this.tableHelper.pageIndex, this.tableHelper.pageSize, this.params
    ).pipe(finalize(() => {
      this.tableHelper.loading = false;
    })).subscribe((result) => {
      this.tableHelper.items = result.result.fieldList;
      this.tableHelper.totalCount = result.result.totalRow;
    });
  }


  reset() {
    this.routeParams = {
      launchsiteId: '', destinationsiteId: '', containerCode: '', containerStatus: [1, 3, 5]
    };
    this.load();
  }

  showLogisticModal(id: string) {
    this.logisticDetailModal.show(id);
  }

  showProductModal(id: string) {
    this.productDetailModal.show(id);
  }

  showWarnInfo(id: string) {
    this.reportAddressModal.show(id);
  }

  showAddress(id: string, code: string) {
    this.realOnlineModal.show(id, code);
  }
  showHistoryInfo(id: string) {
    this.historyPathModal.show(id);
  }

  viewArrivedPlan() {
    this.arrivedPlanModal.show();
  }


  exportToExcel(): void {
    const nameValues: abp.INameValue[] = [];
    nameValues.push({ name: 'limit', value: this.tableHelper.pageSize });
    nameValues.push({ name: 'page', value: this.tableHelper.pageSize });
    nameValues.push({ name: 'option', value: this.params });
    const queryString = abp.utils.buildQueryString(nameValues);
    const exportUrl = this.serviceIpUrl + '/api/center/dpr/dispatch/export' + queryString; // 以上为导出url的拼装，可自行拼装，直接一行拼起来也行

    const options: any = {
      responseType: 'blob',
      headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json' })
    };

    this.httpClient.get(exportUrl, options).subscribe(res => {
      const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });// excel专用，其他请自行查阅资料
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      const fileName = this.l('container_dispath_plan') + moment().format('YYYYMMDDHHmmss') + '.xlsx';
      a.setAttribute('download', fileName);
      a.click();
      URL.revokeObjectURL(objectUrl);

    });
  }
}
